<template>
  <div class="common-layout">
    <el-container>
      <el-header>
        <div class="">
          <p style="float: right; font-size: 14px;">欢迎你、{{ user?user.name:'' }}, <a href="javascript:;" @click="logout">退出</a></p>
          <h1>卓克艺术网采集中心</h1>
        </div>
      </el-header>
      <el-main>
        <div style="text-align: right;">
          <el-button type="primary" @click="showAdd" >新增采集</el-button>
          <el-button type="success" @click="updateCollect" >更新规则</el-button>
          <el-button type="success" @click="testRoute" >调试</el-button>
        </div>
        <el-tabs id="ssss" v-model="activeName" class="demo-tabs" @tab-click="handleClick">
          <el-tab-pane label="拍卖列表" name="0">
            <el-form :inline="true" :model="formInline" class="demo-form-inline">
              <el-form-item label="地址">
                <el-input v-model="formInline.url" placeholder="地址"></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="onSubmit">查询</el-button>
                <el-button @click="getList()">重置</el-button>
              </el-form-item>
            </el-form>
            <el-table :data="tableData" style="width: 100%">
              <el-table-column prop="id" label="ID" width="250" />
              <el-table-column prop="url" label="地址" />
              <el-table-column prop="zc_num" label="专场数量" />
              <el-table-column prop="art_num" label="艺术品数量" />
              <el-table-column prop="remark" label="备注" />
              
              <el-table-column prop="created_at" label="创建时间" width="100"  />
              <el-table-column prop="updated_at" label="更新时间" width="100"  />
              <el-table-column align="right">
                <template #default="scope">
                  <el-button
                    size="small"
                    type="success"
                    @click="handleShowAuctionZc(scope.$index, scope.row)"
                    >选择专场</el-button
                  >
                  <el-button
                    size="small"
                    type="danger"
                    @click="handleDelete(scope.$index, scope.row)"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="专场列表" name="1">
            <el-table v-if="zcList.length>0" :data="zcList">
            <el-table-column property="id" label="ID" width="150" />
            <el-table-column property="url" label="地址" />
            <el-table-column property="title" label="专场名称" width="150" />
            <el-table-column property="date" label="拍卖时间" width="200" />
            <el-table-column property="address" label="拍卖地址" />
            <el-table-column
                prop="status"
                label="状态"
                width="100"
                :filters="[
                  { text: '未采集', value: '1' },
                  { text: '已完成', value: '2' },
                ]"
                :filter-method="filterData"
                filter-placement="bottom-end"
              >
                <template #default="scope">
                  <el-tag
                    :type="scope.row.status == '0' ?'info':scope.row.status == '1'?'': 'success'"
                    disable-transitions
                    >{{ scope.row.status == 1?'未采集':'已完成' }}</el-tag
                  >
                </template>
              </el-table-column>
              <el-table-column prop="created_at" label="创建时间" width="100"  />
          </el-table>
          </el-tab-pane>
          <el-tab-pane label="艺术品列表" name="2">
            <el-table v-if="artList.length>0" :data="artList">
              <el-table-column property="id" label="ID" width="150" />
              <el-table-column property="url" label="地址" />
              <el-table-column property="title" label="作品名称" width="150" />
              <el-table-column
                  prop="status"
                  label="状态"
                  width="100"
                  :filters="[
                    { text: '未采集', value: '0' },
                    { text: '已完成', value: '1' },
                  ]"
                  :filter-method="filterData"
                  filter-placement="bottom-end"
                >
                  <template #default="scope">
                    <el-tag
                      :type="scope.row.status == '0' ?'info': 'success'"
                      disable-transitions
                      >{{ scope.row.status == 0?'未采集':'已完成' }}</el-tag
                    >
                  </template>
                </el-table-column>
                <el-table-column prop="created_at" label="创建时间" width="100"  />
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="适配的站点" name="3">
            <el-table :data="collect" style="width: 100%">
              <el-table-column prop="id" label="ID" width="250" />
              <el-table-column prop="name" label="名称" />
              <el-table-column prop="domain" label="地址" />
              <el-table-column prop="created_at" label="创建时间" width="100"  />
              <el-table-column prop="updated_at" label="更新时间" width="100"  />
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="采集日志" name="4">
            <el-button type="success" @click="getLog" style="float: right;">刷新</el-button>
            <el-row>
              <el-col :span="12">
                <div v-html="logSuccess" class="logs"></div>
              </el-col>
              <el-col :span="12">
                <div v-html="logError" class="logs"></div>
              </el-col>
            </el-row>
          </el-tab-pane>
        </el-tabs>


        <el-drawer
          v-model="showAuctionZc"
          title="选择专场"
          direction="rtl"
          size="80%"
        >
          <div style="text-align: right;">
            <el-popover
              placement="top-start"
              title="注意"
              :width="200"
              trigger="hover"
              content="状态：已入库，则在点击直接取消入库。若已采集需要采集专场结果，重新入库则更新数据"
            >
              <template #reference>
                <el-button type="primary" @click="joinDatabase">入库\取消</el-button>
              </template>
            </el-popover>

            
            <el-popover
              placement="top-start"
              title="注意"
              :width="200"
              trigger="hover"
              content="仅仅只是重新拉取专场列表，已入库的不能更新"
            >
              <template #reference>
                <el-button type="success" @click="repeateShowZcList">重新拉取专场</el-button>
              </template>
            </el-popover>
            
          </div>
          <el-table v-if="auctionCurrent" :data="auctionCurrent.zcList" @selection-change="handleSelectionChangeZc">
            <el-table-column type="selection" width="55" />
            <el-table-column property="title" label="专场名称" width="150" />
            <el-table-column property="date" label="拍卖时间" width="200" />
            <el-table-column property="address" label="拍卖地址" />
            <el-table-column
                prop="status"
                label="状态"
                width="100"
                :filters="[
                  { text: '待入库', value: '0' },
                  { text: '未采集', value: '1' },
                  { text: '已完成', value: '2' },
                ]"
                :filter-method="filterTag"
                filter-placement="bottom-end"
              >
                <template #default="scope">
                  <el-tag
                    :type="scope.row.status == '0' ?'info':scope.row.status == '1'?'': 'success'"
                    disable-transitions
                    >{{ scope.row.status == 0?'待入库': scope.row.status == 1?'未采集':'已完成' }}</el-tag
                  >
                </template>
              </el-table-column>
              <el-table-column prop="created_at" label="创建时间" width="100"  />
          </el-table>
        </el-drawer>
        
      </el-main>
    </el-container>
  </div>
</template>
<script>
import { removeToken } from '@/utils/auth'
import { getCache, setCache } from '@/utils/cache'
import { getToken } from '@/utils/auth'
import ApiLocal from '@/api/local'
import Api from '@/api/index'
import md5 from 'crypto-js/md5'

export default {
  data() {
    return {
      user: this.$store.state.user,
      collect: getCache('collect'),
      tableData: [],
      activeName: '0',
      showAuctionZc: false,
      auctionCurrent: null,
      multipleSelectionZc: [],
      //zc 列表
      zcList: [],
      artList: [],

      logSuccess: '',
      logError: '',
      formInline: {
        url: ''
      }
    };
  },
  created(){
    this.getList()
    console.log(this.$ipc)
    this.getLog()
    Api.getUser({}).then(res=> {

    })
  },
  methods: {
    getList(){
      ApiLocal.collect({token: getToken()}).then(res=> {
        this.tableData = res.list
      })
    },
    showAdd () {
      var collect = this.collect
      this.$messageBox.prompt('请输入需要采集的地址', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValidator: (res)=>{
          if(res.indexOf('.')<0 || res.length == 0)return false
          for(var i in collect) {
            if(res.indexOf(collect[i]['domain'])>=0) return true
          }
          return false
        },
        // inputPattern: 
        inputErrorMessage: '请输入正确的地址/地址没有加入适配库',
      }).then(({ value }) => {
        var collect_id = 0
        for(var i in collect) {
            if(value.indexOf(collect[i]['domain'])>=0) {
              collect_id = collect[i]['id']
              break
            }
        }
        ApiLocal.collectAdd({id: md5(value), url: value, status: 0, remark: '', collect_id: collect_id}).then(res=> {
          if(res && res.code == 1) {
            this.$message({
                message: '新增成功，请点击选择专场！',
                type: 'success',
                onClose: r => {
                  this.getList()
                }
              })
          }
          console.log(res)
        })
      })
    },
    handleShowAuctionZc(index, row){
      ApiLocal.collectShow({id: row.id}).then(res=> {
        this.showAuctionZc = true
        var auctionCurrent = res.info
        auctionCurrent['zcList'] = res.zcList
        this.auctionCurrent = auctionCurrent
      })
    },
    repeateShowZcList(){
      ApiLocal.collectShow({id: this.auctionCurrent.id, requestData: 1}).then(res=> {
        this.$message({
          showClose: true,
          message: '拉取成功',
          type: 'success',
        })
        this.auctionCurrent = res.info
      })
    },
    collectZcResult(){
      if(this.multipleSelectionZc.length == 0) {
        this.$message({
          showClose: true,
          message: '请选择需要采集结果的专场',
          type: 'error',
        })
        return 
      }
      //更新艺术品状态为采集结果
      ApiLocal.updateArtStatus({ids: this.multipleSelectionZc}).then(res=> {
        this.$message({
          showClose: true,
          message: '操作成功',
          type: 'success',
        })
      })
    },
    handleSelectionChangeZc(val){
      this.multipleSelectionZc = val
    },
    joinDatabase(){
      if(this.multipleSelectionZc.length == 0) {
        this.$message({
          showClose: true,
          message: '请选择需要入库的专场',
          type: 'error',
        })
        return 
      }
      ApiLocal.updateZcStatus({ids: this.multipleSelectionZc}).then(res=> {
        this.$message({
          showClose: true,
          message: '操作成功',
          type: 'success',
        })
        var list = this.auctionCurrent.zcList
        for(var i in list) {
          for(var a in this.multipleSelectionZc) {
            if(this.multipleSelectionZc[a]['id'] == list[i]['id']) {
              list[i]['status'] = list[i]['status'] ==1?0:1
              break
            }
          }
          this.auctionCurrent.zcList = list
          // this.$set(, 'zcList', list)
        }


      })
    },
    getZcList(){
      ApiLocal.listZc({}).then(res=> {
        this.zcList = res.list
      })
    },
    getArtList(){
      ApiLocal.listArt({}).then(res=> {
        this.artList = res.list
      })
    },
    handleDelete(index, row){
      this.$confirm('此操作将永久删除拍卖、专场、艺术品, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            const data = {
              id: row.id
            }
            ApiLocal.collectDelete(data).then(res => {
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
              this.tableData.splice(index, 1)
            })
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            })
          })

    },
    updateCollect(){
      Api.index().then(res=> {
        setCache('collect', res.collect)
      })
      ApiLocal.updateCollectConfig({}).then(res=> {
        this.$message({
          type: 'success',
          message: '更新成功!'
        })
      })
    },
    getLog(){
      ApiLocal.log({}).then(res=> {
        this.logSuccess = res.success
        this.logError = res.error
      })
    },
    filterData(value, row, column){
      const property = column['property']
      console.log(row[property])
      return row[property] == value
    },
    handleClick(current){
      if(current.index == 1) {
        this.getZcList()
      }else if(current.index == 2) {
        this.getArtList()
      }
      console.log(current.index)
    },
    logout(){
      removeToken()
      this.$router.push({name: 'Login'})
    },
    testRoute(){
      this.$router.push({name: 'TestRule'})
    },
    onSubmit(){
      ApiLocal.collect({url: this.formInline.url}).then(res=> {
        this.tableData = res.list
      })
    }
  }
};
</script>
